package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Set;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.kenuo.domain.PoloSmsLog;
import com.ruoyi.kenuo.service.IPoloSmsLogService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Api(value = "系统登录相关",tags = "系统登录相关")
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private IPoloSmsLogService poloSmsLogService;

    @Autowired
    private ISysUserService userService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "username", value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query", name = "password", value = "密码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query", name = "code", value = "图文验证码", required = true, dataType = "String")
    })
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) throws Exception
    {
        //解密
        String JmPassword = RsaUtilClient.decryptByPrivateKey("",loginBody.getPassword());
        //经度
        String lgt = loginBody.getLgt();
        //纬度
        String lat = loginBody.getLat();
        //省
        String province = loginBody.getProvince();
        //市
        String city = loginBody.getCity();
        //区
        String area = loginBody.getArea();
        String username = loginBody.getUsername();

        AjaxResult ajax = AjaxResult.success();
        /**先判断用户是否为空，为空就返回错误提醒**/
        if(StrUtil.isNotEmpty(username)){
            SysUser cu = userService.getUserByUserName(username);
            if(ObjUtil.isEmpty(cu)){
                return ajax.error("此账号不存在!");
            }else{
                //用户存在的时候，去更新经纬度
                if(StringUtils.isNotEmpty(lgt)&&StringUtils.isNotEmpty(lat)){
                    SysUser suu = new SysUser();
                    suu.setUserName(username);
                    suu.setLat(lat);
                    suu.setLgt(lgt);
                    if(StringUtils.isNotEmpty(province)){
                        suu.setProvince(province);
                    }
                    if(StringUtils.isNotEmpty(city)){
                        suu.setCity(city);
                    }
                    if(StringUtils.isNotEmpty(area)){
                        suu.setArea(area);
                    }
                    userService.updateUserByUserName(suu);
                }
            }
        }else{
            return ajax.error("参数username不能为空！");
        }
        // 生成令牌
        String token = loginService.login(username, JmPassword, loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
    @PostMapping("/EnLogin")
    public AjaxResult EnLogin(@RequestBody LoginBody loginBody) throws Exception
    {
        //解密
        String JmPassword = RsaUtilClient.decryptByPrivateKey("",loginBody.getPassword());
        //经度
        String lgt = loginBody.getLgt();
        //纬度
        String lat = loginBody.getLat();
        //省
        String province = loginBody.getProvince();
        //市
        String city = loginBody.getCity();
        //区
        String area = loginBody.getArea();



        AjaxResult ajax = AjaxResult.success();
        String username = loginBody.getUsername();
        //加密传输的解密
        if(StringUtils.isNotEmpty(username)){
            username = RsaUtilClient.decryptByPrivateKeyTwo("",username);
        }else{
            return ajax.error("参数username不能为空！");
        }

        /**先判断用户是否为空，为空就返回错误提醒**/
        if(StrUtil.isNotEmpty(username)){
            SysUser cu = userService.getUserByUserName(username);
            if(ObjUtil.isEmpty(cu)){
                return ajax.error("此账号不存在!");
            }else{
                //用户存在的时候，去更新经纬度
                if(StringUtils.isNotEmpty(lgt)&&StringUtils.isNotEmpty(lat)){
                    SysUser suu = new SysUser();
                    suu.setUserName(username);
                    suu.setLat(lat);
                    suu.setLgt(lgt);
                    if(StringUtils.isNotEmpty(province)){
                        suu.setProvince(province);
                    }
                    if(StringUtils.isNotEmpty(city)){
                        suu.setCity(city);
                    }
                    if(StringUtils.isNotEmpty(area)){
                        suu.setArea(area);
                    }
                    userService.updateUserByUserName(suu);
                }
            }
        }
        // 生成令牌
        String token = loginService.login(username, JmPassword, loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
    /**
     * 医生端app登录
     * @Date 20230905
     *
     */
    @PostMapping("/doctorAppLogin")
    public AjaxResult doctorAppLogin(@RequestBody LoginBody loginBody) throws Exception
    {
        String eps = loginBody.getPassword();
        String JmPassword = "";
        //解密
        if(StrUtil.isNotEmpty(eps)){
            //解密-此处是明文
            eps = RsaUtilClient.decryptByPrivateKey("",eps);
            if (eps.length() < UserConstants.PASSWORD_MIN_LENGTH
                    || eps.length() > UserConstants.PASSWORD_MAX_LENGTH)
            {
                return AjaxResult.error("密码长度必须在5到20个字符之间");
            }
            JmPassword =  eps;//RsaUtilClient.decryptByPrivateKey("",eps);
        }else{
            JmPassword = "kenuo1@23";
        }
        //经度
        String lgt = loginBody.getLgt();
        //纬度
        String lat = loginBody.getLat();

        //省
        String province = loginBody.getProvince();
        //市
        String city = loginBody.getCity();
        //区
        String area = loginBody.getArea();

        //手机验证码
        String telCode = loginBody.getTelCode();

        //手机验证码不为空的时候才解密
        if(StringUtils.isNotEmpty(telCode)){
            telCode = RsaUtilClient.decryptByPrivateKeyTwo("",telCode);
        }
        //账号
        String username = loginBody.getUsername();
        if(StringUtils.isNotEmpty(username)){
            username = RsaUtilClient.decryptByPrivateKeyTwo("",username);
        }

        AjaxResult ajax = AjaxResult.success();

        /**先判断用户是否为空，为空就返回错误提醒**/
        if(StrUtil.isNotEmpty(username)){
            SysUser cu = userService.getUserByUserName(username);
            if(ObjUtil.isEmpty(cu)){
                 return AjaxResult.error("此账号不存在!");
            }else{
                if(!cu.getUserType().equals("02")){
                    return AjaxResult.error("此账号已被注册到患者端，不能重复使用!");
                }

                //用户存在的时候，去更新经纬度
                if(StringUtils.isNotEmpty(lgt)&&StringUtils.isNotEmpty(lat)){
                    SysUser suu = new SysUser();
                    suu.setUserName(username);
                    suu.setLat(lat);
                    suu.setLgt(lgt);
                    if(StringUtils.isNotEmpty(province)){
                        suu.setProvince(province);
                    }
                    if(StringUtils.isNotEmpty(city)){
                        suu.setCity(city);
                    }
                    if(StringUtils.isNotEmpty(area)){
                        suu.setArea(area);
                    }
                    userService.updateUserByUserName(suu);
                }
            }
        }else{
            return AjaxResult.error("参数username不能为空！");
        }
        //验证手机验证码
       if(StringUtils.isNotEmpty(username)&&StringUtils.isNotEmpty(telCode)){
            PoloSmsLog poloSmsLog = new PoloSmsLog();
            poloSmsLog.setUserPhone(username);
            poloSmsLog.setMobileCode(telCode);
            Boolean bl = poloSmsLogService.checkCurCode(poloSmsLog);
            if(!bl){
                return AjaxResult.error("验证码不正确！");
            }
        }

        // 生成令牌
        String token = loginService.login(username, JmPassword, loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("APP端登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "username", value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query", name = "telCode", value = "手机验证码", required = false, dataType = "String")
    })
    @PostMapping("/appLogin")
    public AjaxResult appLogin(@RequestBody LoginBody loginBody) throws Exception
    {
        String eps = loginBody.getPassword();
        String userType = loginBody.getUserType();
        String JmPassword = "";
        //解密
        if(StrUtil.isNotEmpty(eps)){
            //解密-此处是明文
            eps = RsaUtilClient.decryptByPrivateKey("",eps);
            if (eps.length() < UserConstants.PASSWORD_MIN_LENGTH
                    || eps.length() > UserConstants.PASSWORD_MAX_LENGTH)
            {
              return AjaxResult.error("密码长度必须在5到20个字符之间");
            }
            JmPassword =  eps;//RsaUtilClient.decryptByPrivateKey("",eps);
        }else{
            JmPassword = "kenuo1@23";
        }

        //省
        String province = loginBody.getProvince();
        //市
        String city = loginBody.getCity();
        //区
        String area = loginBody.getArea();
        //经度
        String lgt = loginBody.getLgt();
        //纬度
        String lat = loginBody.getLat();

        //手机验证码
        String telCode = loginBody.getTelCode();
        //手机验证码不为空的时候才解密
        if(StringUtils.isNotEmpty(telCode)){
            telCode = RsaUtilClient.decryptByPrivateKeyTwo("",telCode);
        }
        //账号
        String username = loginBody.getUsername();
        if(StringUtils.isNotEmpty(username)){
            username = RsaUtilClient.decryptByPrivateKeyTwo("",username);
        }
        //手机号码
        String telNum = loginBody.getTelNum();
        AjaxResult ajax = AjaxResult.success();

        /**先判断用户是否为空，为空就先去注册**/
        if(StrUtil.isNotEmpty(username)){
            SysUser cu = userService.getUserByUserName(username);
            if(ObjUtil.isEmpty(cu)){
                SysUser sur = new SysUser();
                sur.setUserName(username);
                String jpas =  SecurityUtils.encryptPassword(JmPassword);
                sur.setPassword(jpas);
                sur.setDelFlag("0");
                if(StringUtils.isNotEmpty(userType)){
                    sur.setUserType(userType);
                }else {
                    sur.setUserType("02");
                }

                sur.setSysFlag(2);
                sur.setStatus("0");
                sur.setNickName(username);
                sur.setProvince(province==null?"":province);
                sur.setCity(city==null?"":city);
                sur.setArea(area==null?"":area);
                sur.setLoginDate(DateUtils.getNowDate());
                sur.setCreateTime(DateUtils.getNowDate());
                sur.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
                sur.setLoginDate(DateUtils.getNowDate());
                sur.setLat(lat==null?"":lat);
                sur.setLgt(lgt==null?"":lgt);
                sur.setPhonenumber(telNum);
                boolean regFlag = userService.registerUser(sur);
                if(!regFlag){
                  return AjaxResult.error("登录失败，系统异常！");
                }
            }else{
                if(!cu.getUserType().equals("03")){
                    return AjaxResult.error("此账号已被注册到医生端，不能重复使用!");
                }
                //用户存在的时候，去更新经纬度
                if(StringUtils.isNotEmpty(lgt)&&StringUtils.isNotEmpty(lat)){
                    SysUser suu = new SysUser();
                    suu.setUserName(username);
                    suu.setLat(lat);
                    suu.setLgt(lgt);
                    if(StringUtils.isNotEmpty(province)){
                        suu.setProvince(province);
                    }
                    if(StringUtils.isNotEmpty(city)){
                        suu.setCity(city);
                    }
                    if(StringUtils.isNotEmpty(area)){
                        suu.setArea(area);
                    }
                    userService.updateUserByUserName(suu);
                }
            }

        }else{
            return AjaxResult.error("参数username不能为空！");
        }


        //验证手机验证码
        if(StringUtils.isNotEmpty(username)&&StringUtils.isNotEmpty(telCode)){
            PoloSmsLog poloSmsLog = new PoloSmsLog();
            poloSmsLog.setUserPhone(username);
            poloSmsLog.setMobileCode(telCode);
            Boolean bl = poloSmsLogService.checkCurCode(poloSmsLog);
            if(!bl){
                return AjaxResult.error("验证码不正确！");
            }
        }

        // 生成令牌
        String token = loginService.login(username, JmPassword, loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation("获取当前登录的用户信息--无参数")
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }
    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getMyInfo")
    public AjaxResult getMyInfo(String userName) throws Exception {

        if(StringUtils.isNotEmpty(userName)){
            userName = RsaUtilClient.decryptByPrivateKeyTwo("",userName);
        }
        SysUser user = userService.getUserByUserName(userName);
        String username = user.getUserName();
        String phonenumber = user.getPhonenumber();
        if(StringUtils.isNotEmpty(username)){
            userName = RsaUtilClient.encryptByPublicKeyTwo(username);
            user.setUserName(userName);
        }
        if(StringUtils.isNotEmpty(phonenumber)){
            phonenumber = RsaUtilClient.encryptByPublicKeyTwo(phonenumber);
            user.setPhonenumber(phonenumber);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        return ajax;
    }
    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
